<template>
  <section class="sample-section"  v-loading.lock="loading" element-loading-text="拼命加载中">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>批次信息</span>
      </div>
      <el-table :data="[tradeBatch]" border style="width: 100%">
        <el-table-column align="center" prop="company_title" label="支付企业"></el-table-column>
        <el-table-column align="center" prop="batch_number" label="批次号"></el-table-column>
        <el-table-column align="center" prop="pay_status" label="支付状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.pay_status === -1" size="small" type="warning">打款失败</el-tag>
            <el-tag v-else-if="scope.row.pay_status === 1" size="small" type="">等待打款</el-tag>
            <el-tag v-else-if="scope.row.pay_status === 2"  size="small" type="">打款中</el-tag>
            <el-tag v-else-if="scope.row.pay_status === 3" size="small" type="warning">部分打款</el-tag>
            <el-tag v-else-if="scope.row.pay_status === 9" type="success">打款成功</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="pay_money" label="支付总额">
          <template slot-scope="scope">
            <span>{{scope.row.pay_money|numFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="money_service" label="服务费总额">
          <template slot-scope="scope">
            <span>{{scope.row.pay_money - scope.row.settle_money|numFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="settle_money" label="实付总额">
          <template slot-scope="scope">
            <span>{{scope.row.settle_money|numFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="pay_error_msg" label="错误信息">
          <template slot-scope="scope">
            <span v-if="scope.row" :class="scope.row.status_pay === '打款失败' ? 'error' : ''">{{scope.row.pay_error_msg}}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>付款明细</span>
      </div>
      <el-form :model="dataForm" @keyup.enter.native="getDataList()" label-width="120px">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="12" :lg="4" :xl="4">
            <el-form-item label="收款方姓名" prop="pay_name">
              <el-input v-model="dataForm.pay_name" type="text" placeholder="收款方姓名" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="4" :xl="4">
            <el-form-item label="收款方账号" prop="pay_account">
              <el-input v-model="dataForm.pay_account" type="text" placeholder="收款方账号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="4" :xl="4">
            <el-form-item label="付款状态" prop="pay_status">
              <el-select v-model="dataForm.pay_status" placeholder="请选择付款状态">
                <el-option
                  v-for="item in pay_status_text"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="20" :sm="20" :md="12" :lg="6" :xl="6">
            <el-form-item>
              <el-button type="primary" @click="getData()">查询</el-button>
              <el-button type="danger" @click="downloadfile">明细导出</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="tableData" v-loading="isLoading"
                :row-class-name="handleRowClassName"
                @cell-click="clickHandle" style="width: 100%">
        <el-table-column align="center" prop="id" width="80px" sortable="custom" label="ID">
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="pay_type" label="账号类型"></el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="pay_name" label="收款方账户姓名"></el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="pay_amount" label="收款方客户账号"></el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="status_pay" label="付款状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.pay_status === -1" size="small" type="warning">打款失败</el-tag>
            <el-tag v-else-if="scope.row.pay_status === 1" size="small" type="">等待打款</el-tag>
            <el-tag v-else-if="scope.row.pay_status === 2"  size="small" type="">打款中</el-tag>
            <el-tag v-else-if="scope.row.pay_status === 3" size="small" type="warning">部分打款</el-tag>
            <el-tag v-else-if="scope.row.pay_status === 9" type="success">打款成功</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="pay_remark" label="付款备注"></el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="pay_money" label="支付总额">
          <template slot-scope="scope">
            <span>{{scope.row.pay_money|numFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="settle_money" label="实付总额">
          <template slot-scope="scope">
            <span>{{scope.row.settle_money|numFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="pay_time" label="付款时间">
          <template slot-scope="scope">
            <span>{{scope.row.pay_time ? scope.row.pay_time :  '--'}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip prop="error_msg" label="错误信息">
          <template slot-scope="scope">
            <span v-if="scope.row" :class="scope.row.pay_status === -1 ? 'error' : ''">{{scope.row.pay_message}}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          width="240px"
          label="操作">
          <template slot-scope="scope">
            <el-button :disabled="scope.row.pay_status !== 1 && scope.row.pay_status !== -1" @click="openManualDialog(scope.row)" size="mini" type="primary">手动打款</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="buttons" v-if="tradeBatch.pay_status === 1 || tradeBatch.pay_status === -1">
      <el-button type="danger" v-if="tradeBatch.pay_status === 1" @click="launchPay()" >批量付款</el-button>
      <el-button type="warning" @click="openDialog()" >批量手动付款</el-button>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="手动打款"
      :visible.sync="manualPaydialogVisible"
      width="600px">
      <el-form :model="formData" ref="form" label-width="100px">
        <el-form-item label="备注信息" prop="pay_message">
          <el-input style="width: 400px;" type="textarea" :rows="5" v-model="formData.pay_message"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="manualPaydialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="支付确认"
      :visible.sync="payBatchdialogVisible"
      width="600px">
      <span v-if="loadingSendSms" class="danger-text">正在发起支付...请稍后...</span>
      <el-form :model="BatchData" ref="form" label-width="100px" v-else>
        <span class="sms-tip">
          短信验证码已发送到
          <span class="danger-text">{{BatchData.operator_tel_no}}</span>
        </span>
        <span class="sms-tip">
          本次交易笔数
          <span class="danger-text">{{BatchData.total_count}}</span>
          交易总金额
          <span class="danger-text">￥{{BatchData.total_amount}}</span>
        </span>
        <el-form-item label="验证码" prop="pay_message">
          <el-input v-model="BatchData.sms_code"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="!loadingSendSms">
        <el-button @click="cancelBatchDialog()">取 消</el-button>
        <el-button type="primary" @click="payBatchSubmit()" :loading="isSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="批量付款"
      :visible.sync="paydialogVisible"
      width="600px">
      <el-form :model="formData" ref="form" label-width="100px">
        <el-form-item label="付款凭证" prop="proof">
          <el-upload class="uploadBtn" ref="upload"
                     :action="getUrl('proof')"
                     :headers="{ token: $cookie.get('token') }"
                     :before-upload="beforeUploadHandle"
                     :on-change="handleFileChange"
                     :on-success="handleUploadSuccess"
                     :on-error="handleUploadError"
                     :file-list="formData.fileList"
                     :auto-upload="true">
            <el-button type="primary" size="small">浏览</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注信息" prop="pay_message">
          <el-input style="width: 400px;" type="textarea" :rows="5" v-model="formData.pay_message"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog()">取 消</el-button>
        <el-button type="primary" @click="batchSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
    export default {
      name: "details",
      data() {
        return {
          loading: false,
          id: '',
          dataForm: {
            pay_name: '',
            pay_account: '',
            pay_status: '',
          },
          pay_status_text: [{
            value: '',
            label: "全部"
          },{
            value: '-1',
            label: "打款失败"
          },{
            value: '1',
            label: "等待打款"
          },{
            value: '2',
            label: "打款中"
          },{
            value: '9',
            label: "打款成功"
          }],
          tradeBatch: {
            batch_id: '',
            batch_number: '',
            company_title: '',
            created_at: '',
            pay_money: '',
            settle_money: '',
            type: 0,
            rate: 0,
            pay_status: 0
          },
          manualPaydialogVisible: false,
          paydialogVisible: false,
          payBatchdialogVisible: false,
          formData: {
            pay_message: '',
            pay_proof: '',
            trade_batch_id: '',
            id: '',
            file_name: '',
            fileList: []
          },
          BatchData: {
            sms_code: '',
            operator_tel_no: '',
            total_amount: '',
            total_count: '',
            file: '',
          },
          isSubmit: false,
          loadingSendSms: true,
          tableData: []
        }
      },
      activated () {
        this.loading = true
        this.id = this.$route.query ? this.$route.query.id : null;
        this.getData()
      },
      filters: {
        // 截取当前数据到小数点后两位
        numFilter(value) {
          const realVal = parseFloat(value).toFixed(2);
          return realVal;
        }
      },
      methods: {
        getData() {
          if(!this.id) {
            this.$message.error("请求参数错误")
            this.$parent.$parent.$parent.$parent.tabsCloseCurrentHandle()
            this.$router.push({ name: 'payment-list'})
          }
          this.$http({
            url: this.$http.adornUrl(`/payment/info/${this.id}`),
            method: 'get',
            params: this.$http.adornParams({
              id: this.id,
              pay_name: this.dataForm.pay_name,
              pay_account: this.dataForm.pay_account,
              pay_status: this.dataForm.pay_status,
            })
          }).then((result) => {
            let _data = result.data.data
            this.tradeBatch.id = _data.id
            this.tradeBatch.company_title = _data.company_info.title
            this.tradeBatch.batch_number = _data.batch_number
            this.tradeBatch.pay_status = _data.pay_status
            this.tradeBatch.pay_money = _data.pay_money
            this.tradeBatch.settle_money = _data.settle_money

            this.tableData = _data.trade_record
          })
          setTimeout(() => {
            this.loading = false
          }, 500);
        },
        downloadfile() {
          this.loading = true
          this.$http({
            url: this.$http.adornUrl(`/payment/export/${this.id}`),
            method: 'get',
            responseType: 'blob'
          }).then((res) => {
            let _data = res.data
            let blob = new Blob([_data])
            let reader = new FileReader()
            reader.readAsDataURL(blob)
            reader.onload = (e) => {
              let a = document.createElement('a')
              a.download = '付款明细.csv'
              a.href = e.target.result
              document.body.appendChild(a)
              a.click()
              a.remove()
            }
            this.loading = false;
          }).catch(() =>{
            this.loading = false;
          })
        },
        submitData() {
          let _self = this
          this.$http({
            url: this.$http.adornUrl(`/payment/manual_payment/${this.formData.id}`),
            method: 'post',
            params: this.$http.adornParams({
              pay_message: this.formData.pay_message
            })
          }).then((result) => {
            let _data = result.data
            if(_data.code === 0) {
              this.$message.success('操作成功')
              this.manualPaydialogVisible = false
              setTimeout(function() {
                _self.getData();
              }, 1500)
            } else {
              this.$message.error(_data.msg)
            }
          })
        },
        launchPay() {
          this.loadingSendSms = true
          this.payBatchdialogVisible = true
          this.$http({
            url: this.$http.adornUrl(`/payment/launch/pay/${this.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then((result) => {
            let res = result.data

            if(res.code === 0) {
              this.BatchData.operator_tel_no = res.data.operator_tel_no
              this.BatchData.total_count = res.data.total_count
              this.BatchData.total_amount = res.data.total_amount
              this.BatchData.file = res.data.file
            } else {
              this.$message.error(res.msg)
              this.payBatchdialogVisible = false
            }
            this.loadingSendSms = false
          })
        },
        payBatchSubmit() {
          if(this.BatchData.sms_code == '') {
            this.$message.error("请输入验证码");
            return false
          }
          this.isSubmit = true
          this.$http({
            url: this.$http.adornUrl(`/payment/confirm/pay`),
            method: 'POST',
            params: this.$http.adornParams({
              id: this.id,
              sms_code: this.BatchData.sms_code,
              total_amount: this.BatchData.total_amount,
              total_count: this.BatchData.total_count,
              file: this.BatchData.file
            })
          }).then((result) => {
            let res = result.data
            if(res.code === 0) {
              this.$message.success('操作成功')
              setTimeout(() => {
                this.getData()
                this.payBatchdialogVisible = false
              }, 1500)
            } else {
              this.$message.error(res.msg)
            }
            this.isSubmit = false
          })
        },
        confirmBatchSubmit() {
          this.$http({
            url: this.$http.adornUrl(`/payment/confirm/pay`),
            method: 'post',
            params: this.$http.adornParams({
              pay_proof: this.formData.pay_proof,
              pay_message: this.formData.pay_message
            })
          }).then((result) => {
            let _data = result.data
            if(_data.code === 0) {
              this.$message.success('操作成功')
              this.paydialogVisible = false
            } else {
              this.$message.error(_data.msg)
            }
          })
        },
        batchSubmit() {
          let _self = this
          this.$http({
            url: this.$http.adornUrl(`/payment/batch_payment/${this.formData.trade_batch_id}`),
            method: 'post',
            params: this.$http.adornParams({
              pay_proof: this.formData.pay_proof,
              pay_message: this.formData.pay_message
            })
          }).then((result) => {
            let _data = result.data
            if(_data.code === 0) {
              this.$message.success('操作成功')
              this.paydialogVisible = false
              setTimeout(function() {
                _self.getData();
              }, 1500)
            } else {
              this.$message.error(_data.msg)
            }
          })
        },
        cancelDialog() {
          this.paydialogVisible = false
          this.formData.fileList = []
          this.formData.file_name = ''
          this.formData.pay_proof = ''
          this.formData.trade_batch_id = ''
        },
        cancelBatchDialog() {
          this.payBatchdialogVisible = false
        },
        handleRowClassName({row, rowIndex}) {
          console.log(row)
          if(row.pay_status == -1) {
            return 'is-error'
          }
        },
        beforeUploadHandle(file) {
          console.log(file)
        },
        handleFileChange(file) {
          console.log(file)
          if (file.raw.type !== 'application/pdf' && file.raw.type !== 'application/zip' && file.raw.type !== 'application/gzip') {
            this.$message.error('文件类型错误！支持pdf、zip')
            return false
          }
          if(file.size > 3 * 1024 * 1024) {
            this.$message.error('只支持3M以内的文件上传！')
            return false
          }
          this.formData.file_name = file.name
        },
        handleUploadSuccess(res) {
          console.log(res)
          if(res.code === 0) {
            this.formData.pay_proof = res.path
          } else {
            this.$message.error(res.msg)
            this.formData.fileList = []
            this.$nextTick(() => {
              this.formData.file_name = ''
              this.formData.pay_proof = ''
            })
          }
        },
        handleUploadError() {
          this.formData.fileList = []
          this.$nextTick(() => {
            this.formData.file_name = ''
            this.formData.pay_proof = ''
          })
        },
        getUrl(type) {
          return this.$http.adornUrl(`/sys/oss/upload?type=` + type)
        },
        openDialog() {
          this.paydialogVisible = true
          this.formData = {
            trade_batch_id: this.tradeBatch.id,
            pay_message: '',
            pay_proof:  '',
          }
        },
        openManualDialog(row) {
          this.manualPaydialogVisible = true
          this.formData = {
            id: row.id,
            pay_message: ''
          }
        },
      }
    }
</script>

<style lang="scss" scoped>
  .box-card {
    margin-bottom: 20px;

    /deep/ .is-error {
      .error {
        color: #f56c6c;
      }
    }
  }

  .sms-tip {
    display: block;
    margin-left: 100px;
    font-size: 18px;
    margin-bottom: 10px;
  }

  .buttons {
    margin-top: 15px;
    text-align: center;
  }
</style>
